package com.gmcloud.common.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gmcloud.common.security.config.oauth2.PermitAllUrlProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector;

/**
 * @author zl.sir
 * @version 1.0
 * @since 2022/8/17 1:25
 */

@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(PermitAllUrlProperties.class)
public class GmResourceServerAutoConfiguration {


    /**
     * 鉴权具体的实现逻辑
     * @return （#pms.xxx）
     */
    @Bean("pms")
    public PermissionService permissionService() {
        return new PermissionService();
    }


    /**
     * 请求令牌的抽取逻辑
     * @param urlProperties 对外暴露的接口列表
     * @return BearerTokenExtractor
     */
    @Bean
    public GmBearerTokenExtractor gmBearerTokenExtractor(PermitAllUrlProperties urlProperties) {
        return new GmBearerTokenExtractor(urlProperties);
    }

    /**
     * 资源服务器异常处理
     * @param objectMapper jackson 输出对象
     * @return ResourceAuthExceptionEntryPoint
     */
    @Bean
    public ResourceAuthExceptionEntryPoint resourceAuthExceptionEntryPoint(ObjectMapper objectMapper) {
        return new ResourceAuthExceptionEntryPoint(objectMapper);
    }

    /**
     * 资源服务器toke内部处理器
     * @param authorizationService token 存储实现
     * @return TokenIntrospector
     */
    @Bean
    public OpaqueTokenIntrospector opaqueTokenIntrospector(OAuth2AuthorizationService authorizationService) {
        return new GmCustomOpaqueTokenIntrospector(authorizationService);
    }


    /**
     * @return 密码加密策略
     */
    @Bean
    public BCryptPasswordEncoder encoding(){
        return new BCryptPasswordEncoder();
    }
}
